package gin_helper

import (
	"github.com/gin-gonic/gin"
	"log"
	"regexp"
	"strings"
)

func GetPostData(c *gin.Context) (params map[string]any) {
	params = make(map[string]any)
	if strings.Contains(c.ContentType(), "form-data") {
		data, err := c.MultipartForm()
		if err != nil {
			log.Println("GetPostData()：", err)
		} else {
			for key, values := range data.Value {
				if len(values) == 0 {
					params[key] = ""
				} else if len(values) == 1 {
					params[key] = values[0]
				} else {
					params[key] = values
				}
			}
		}
	} else {
		err := c.ShouldBindJSON(&params)
		if err != nil {
			log.Println("GetPostData()：", err)
		}
	}
	return
}

func Res(c *gin.Context, code int, msg string, data any) {
	c.JSON(200, map[string]any{
		"code": code,
		"msg":  msg,
		"data": data,
	})
}

// 用客户端域名做key，用于存储cookie，验证码等
func GetClientKey(c *gin.Context, prefix string) string {
	//优先找头部的DeviceId
	deviceId := c.GetHeader("DeviceId")
	if deviceId != "" {
		return prefix + "_" + deviceId
	}

	//后找头部的web来源
	origin := c.GetHeader("Origin")
	if origin == "" {
		origin = c.GetHeader("Referer")
	}
	re := regexp.MustCompile(`^(?:https?://)?(?:www\.)?([^/]+)`)
	matches := re.FindStringSubmatch(origin)
	if len(matches) > 1 {
		origin = matches[1]
		origin = strings.ReplaceAll(origin, ".", "_")
		origin = strings.ReplaceAll(origin, ":", "_")
		return prefix + "_" + origin
	}
	log.Println("客户端非H5,无法获取来源，头部也没有携带DeviceId")
	return ""
}
